from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
# from DataCenter.models import Major, Gxxx04, Gxjg0101
from DataCenter import tasks
import json
import datetime
from celery.result import AsyncResult
from DataManagement.utils import MyResponse
from Dashboard.code import AccessCheck


# Create your views here.
'''
def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")
'''



'''
def get_teacher_age():
    now_year = datetime.datetime.now().year

    data = [{
        'item': '30 岁及以下',
        'count': 0,
        'value': 300,
        'percent': 0
    }, {
        'item': '31-35 岁',
        'count': 0,
        'percent': 0
    }, {
        'item': '36-40 岁',
        'count': 0,
        'percent': 0
    }, {
        'item': '41-45 岁',
        'count': 0,
        'percent': 0
    }, {
        'item': '46-50 岁',
        'count': 0,
        'percent': 0
    }, {
        'item': '51-55 岁',
        'count': 0,
        'percent': 0
    }, {
        'item': '56-60 岁',
        'count': 0,
        'percent': 0
    }, {
        'item': '61-65 岁',
        'count': 0,
        'percent': 0
    }, {
        'item': '66 岁及以上',
        'count': 0,
        'percent': 0
    }]
    count = 0
    for item in Gxjg0101.objects.filter(csrq__isnull=False):
        count += 1
        age = now_year - int(item.csrq[0:4])
        if age <= 30:
            data[0]['count'] += 1
        elif age <= 35:
            data[1]['count'] += 1
        elif age <= 40:
            data[2]['count'] += 1
        elif age <= 45:
            data[3]['count'] += 1
        elif age <= 50:
            data[4]['count'] += 1
        elif age <= 55:
            data[5]['count'] += 1
        elif age <= 60:
            data[6]['count'] += 1
        elif age <= 65:
            data[7]['count'] += 1
        else:
            data[8]['count'] += 1

    for item in data:
        item['percent'] = round(item['count'] / count, 4)
        print(item['percent'])

    return data


def get_teacher_degree():
    teacher_age_data = get_teacher_age()
    pass


def index(request):
    teacher_age_data = get_teacher_age()
    data = {
        'teacher_age_date': teacher_age_data
    }
    return render(request, 'DataCenter/index.html', context=data)
'''

def add(request, a, b):
    res = tasks.add.delay(a, b)
    # 任务逻辑
    return JsonResponse({'status': 'successful', 'task_id': res.task_id})


def result(request, task_id):
    res = AsyncResult(task_id)
    if res.ready():
        if res.successful():
            return HttpResponse(res.result)
        else:
            return HttpResponse(res.result)
    else:
        return JsonResponse({'status': 'pending', 'message': '执行中'}, json_dumps_params={'ensure_ascii': False})


def task(request, task_id):
    res = AsyncResult(task_id)
    if res.ready():
        if res.successful():
            return MyResponse.success(**res.result)
        else:
            return MyResponse.failure(res.result)
    else:
        return MyResponse.success(None, '排队执行中，请稍后再试', AccessCheck.PENDING)


def build_recipients(mail):
    if mail not in (
        '543046534@qq.com',
        '403763307@qq.com',  # 耀文
        '623640216@qq.com',
        '924324407@qq.com',  # 陈柔子
        '20210129@dgut.edu.cn'  # 吕有才
    ):
        raise Exception("邮箱不在白名单")

    mail_list = set(['403763307@qq.com'])
    mail_list.add('20210129@dgut.edu.cn')
    if mail in ['924324407@qq.com', '20210129@dgut.edu.cn']:
        mail_list.add('924324407@qq.com')
        mail_list.add('20210129@dgut.edu.cn')
    else:
        mail_list.add(mail)

    return mail_list


def send_file(request, mail):
    mail_list = build_recipients(mail)
    res = tasks.access_check_generate_and_send_report.delay(list(mail_list))

    # 任务逻辑
    # return JsonResponse({'status': 'successful', 'task_id': res.task_id})
    return HttpResponseRedirect('/datacenter/result/{}'.format(res.task_id))
    # return HttpResponse(email.send(fail_silently=False))


def local_send_file(request, mail):
    mail_list = build_recipients(mail)
    res = tasks.access_check_generate_and_send_report(mail_list)
    # 任务逻辑
    # return JsonResponse({'status': 'successful', 'task_id': res.task_id})
    return HttpResponseRedirect('/datacenter/result/{}'.format(res.task_id))
    # return HttpResponse(email.send(fail_silently=False))
